package com.java2;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *  * 实现TCP的网络编程
 *  * 例题2：客户端发送文件给服务端，服务端将文件保存在本地。
 */
public class TCPTest2 {
    //应该使用try-catch-finally来处理异常
    @Test
    public void client() throws IOException{
        Socket socket = new Socket(InetAddress.getLocalHost(), 9090);

        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("01.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        fis.close();
        os.close();
    }

    @Test
    public void server() throws IOException{

        ServerSocket serverSocket = new ServerSocket(9090);
        Socket socket = serverSocket.accept();
        InputStream is = socket.getInputStream();

        FileOutputStream fos = new FileOutputStream(new File("02.jpg"));

        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }

        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}
